<?php

namespace app\api\controller;

use app\api\model\Company as CompanyModel;
use app\store\model\Company as storeCompanyModel;
use app\common\model\company\Category as CategoryModel;
use think\Db;
use app\common\service\qrcode\Birthday;

/**
 * 企业控制器
 * Class Company
 * @package app\api\controller
 */
class Company extends Controller
{
    /**
     *
     * @return array
     */
    public function index()
    {
        // 企业分类列表
        $categoryList = CategoryModel::getALL();
        return $this->renderSuccess(compact('categoryList'));
    }

    /**
     * 企业列表
     * @param int $category_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function lists($cate_id = 0, $team_id = 0, $searchInput = "", $longitude = 0, $latitude = 0)
    {
        $user = $this->getUser();
        $user_id['user_id'] = 0;
        $page1 = 1;
        $param = input('param.');
        if (isset($param['page1'])) {
            $page1 = $param['page1'];
        }
        $model = new CompanyModel;
        $list1 = $model->getList($cate_id, $team_id, $searchInput, 100000, $user_id['user_id'],$user['shanghui_id']);
        if (!$list1['data']) {
            return $this->renderSuccess(['list' => [], 'last_page' => 1]);
        }
        foreach ($list1['data'] as &$value) {
            $value['mi'] = $this->getDistance($value['longitude'], $value['latitude'], $longitude, $latitude);
            $value["birth_day"]='366';
            $value["birth_date"]='';
            $jinNian = "2023";
            $mingNian ="2024";
            $birth_date = (isset($value["user"]["birth_date"]) && $value["user"]["birth_date"])?date("md",strtotime($value["user"]["birth_date"])):"";
            if(!$birth_date){
                // 生日不存在 使用身份证的生日
                if(isset($value["user"]["card_id"]) && $value["user"]["card_id"] && strlen($value["user"]["card_id"])>14){
                    $birth_date = substr($value["user"]["card_id"],10,4);
                }
            }
            // 如果有生日计算还有多少天过生日
            if($birth_date){
                $start = $jinNian.date("md");
                if($birth_date < date("md")){
                    $end   =  $mingNian.$birth_date;
                }else{
                    $end   =  $jinNian.$birth_date;
                }
                $day = date_diff(date_create($start),date_create($end));
                $value["birth_day"] = (int)$day->format('%r%a');
                $value["birth_date"]= substr($birth_date,0,2)."-".substr($birth_date,2,2);
            }
        }

        if (isset($param['isbirthday']) && $param['isbirthday'] =='true') {
            $list = $this->my_sort($list1['data'], 'birth_day', SORT_ASC); //按生日排行
        }else{
            $list = $this->my_sort($list1['data'], 'mi', SORT_ASC); //按距离排行
        }
        foreach ($list as &$v) {
            $v['distance'] = "距您" . $this->mi($v['mi']);
            if (!$v['add_date'] || strtotime($v['add_date']) <= 0) {
                $v['user']['lion_age'] = 0 . '年';
            } else {
                $v['user']['lion_age'] = ceil(date('Y', time()) - date('Y', strtotime($v['add_date']))) . '年';//狮龄
            }
            if (isset($v['user']['nickName'])) {
                $v['user']['nickName'] = str_substr($v['user']['nickName'], 4);
            }
        }
        $last_page = ceil(count($list) / 10);
        $list = array_slice($list, ($page1 - 1) * 10, 10);
        return $this->renderSuccess(compact('list', 'last_page'));
    }

    /**
     * 企业详情
     * @param $Company_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function detail($company_id)
    {
        $detail = CompanyModel::detail($company_id);
        $goods_image = Db::name('company_image')->alias("c")->join("upload_file f", "f.file_id = c.image_id")
            ->where("c.user_id", '=', $detail['user_id'])->select();
        $goods = [];
        foreach ($goods_image as $item) {
            $goods[] = ["id" => $item["image_id"], "url" => $item["file_url"] . "/" . $item["file_name"]];
        }
        $detail['goods'] = $goods;
        if (isset($detail['add_date'])) {
            if (!$detail['add_date'] || strtotime($detail['add_date']) <= 0) {
                $detail['user']['lion_age'] = 0 . '年';
            } else {
                $detail['user']['lion_age'] = ceil(date('Y', time()) - date('Y', strtotime($detail['add_date']))) . '年';//狮龄
            }
        } else {
            $detail['user'] = ['lion_age' => 0 . '年'];
        }

        return $this->renderSuccess(compact('detail'));
    }

    /**
     * 添加/编辑企业
     */
    public function release()
    {
        $param = input('param.');
        $user = $this->getUser();
        $param['team_id'] = $user['team_id'];   //服务队id
        $param['shanghui_id']= $user['shanghui_id']; //商会id
        $param['company_sort'] = 100;//排序目前没啥用
        $companyInfo = Db::name('company')->where('user_id', $user['user_id'])->find();
        if (!$companyInfo) {
            $param['user_id'] = $user['user_id'];
            // 新增记录
            $model = new storeCompanyModel;
            $res = $model->add($param);
            if ($res) {
                //return $this->renderSuccess(["url" => "pages/user/index"], '添加成功');
                return $this->renderSuccess(["url" => ""], '添加成功');
            }
            return $this->renderError($model->getError() ?: '添加失败');
        }
        $model = storeCompanyModel::detail($companyInfo['company_id']);
        $res = $model->edit($param);
        if ($res) {
            //return $this->renderSuccess(["url" => "pages/user/index"], '更新成功');
            return $this->renderSuccess(["url" => ""], '更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 我的企业详情
     * @return array|mixed
     */
    public function companyInfo()
    {
        $user = $this->getUser();
        $detail = Db::name('company')->where('user_id', $user['user_id'])->find();
        if ($detail) {
            $detail['image'] = Db::name('upload_file')->find($detail['image_id']);
            $detail['banner'] = Db::name('upload_file')->find($detail['banner_id']);
            $detail['category'] = Db::name('company_category')->find($detail['category_id']);
            $goods_image = Db::name('company_image')->alias("c")->join("upload_file f", "f.file_id = c.image_id")
                ->where("c.user_id", '=', $user['user_id'])->select();
            $goods = [];
            foreach ($goods_image as $item) {
                $goods[] = ["id" => $item["image_id"], "url" => $item["file_url"] . "/" . $item["file_name"]];
            }
            $detail['goods'] = $goods;
        }
        return $this->renderSuccess(compact('detail'));
    }

    /**
     * 生成生日祝福海报
     * @return array|mixed
     */
    public function birthdayPoster($user_id)
    {
        $user=Db::name("user")->find($user_id);
        if($user){
            $b = new Birthday($user);
            $url = $b->getImage();
            return $this->renderSuccess(compact('url'));
        }
        return $this->renderError('失败，没找到用户！');
    }

    /**
     * 获取两个坐标点的距离
     * @param $ulon
     * @param $ulat
     * @param $slon
     * @param $slat
     * @return float
     */
    private function getDistance($ulon, $ulat, $slon, $slat)
    {
        if (!$ulon) {
            $ulon = 121.549567;
            $ulat = 38.957938;
        }
        // 地球半径
        $R = 6378137;
        // 将角度转为狐度
        $radLat1 = deg2rad($ulat);
        $radLat2 = deg2rad($slat);
        $radLng1 = deg2rad($ulon);
        $radLng2 = deg2rad($slon);
        // 结果
        $s = acos(cos($radLat1) * cos($radLat2) * cos($radLng1 - $radLng2) + sin($radLat1) * sin($radLat2)) * $R;
        // 精度
        $s = round($s * 10000) / 10000;

        return $s;

    }

    public function mi($s)
    {
        if (round($s) > 1000) {
            return round($s / 1000, 2) . "千米";
        } else {
            return round($s) . "米";
        }
    }


    function my_sort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
    {
        if (is_array($arrays)) {
            foreach ($arrays as $array) {
                if (is_array($array)) {
                    $key_arrays[] = $array[$sort_key];
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
        array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
        return $arrays;
    }

}
